<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 首页
 *
 * @author      Eden
 * @datetime    2016/12/17 21:54
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Lists_Model extends API_Model
{

    const LIST_PAGE_SIZE = 20;

    private $nowPage = 1;
    private $total = 0;
    protected $width = 640;
    protected $height = 360;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        if (!empty($params['page']) && intval($params['page']) > 0) {
            $this->nowPage = intval($params['page']);
        }

        $res = $this->_getLists($params);
        $send['state'] = true;
        if (!empty($res)) {
            $send['data'] = array(
                'total' => $this->total,
                'data' => $res,
                'nextPage' => ($this->nowPage * self::LIST_PAGE_SIZE) < $this->total
            );
        } else {
            $send['data'] = array(
                'total' => 0,
                'data' => [],
                'nextPage' => false
            );
        }
        $this->output->send($send);
    }

    /**
     * 列表
     */
    private function _getLists($params = array())
    {
        $tDb = clone($this->db);
        $this->total = $tDb->where('status', 1)->where("stock > 0")->count_all_results('base_goods');

        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, liveUrl, thumbWidth, thumbHeight, expressWeight, streamId, price, minPrice, minPurPrice, created')
            ->from('base_goods')
            ->order_by('modified', 'DESC')
            ->limit(self::LIST_PAGE_SIZE, ($this->nowPage - 1) * self::LIST_PAGE_SIZE)
            ->order_by('created', 'DESC')
            ->where(array('status' => 1))
            ->where("stock > 0")
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return [];
        }

        $userType = $this->getUserType(value($params, 'userId'));

        $results = $goodsIds = [];
        foreach($rows as $item) {
            $wh = $this->countWidthHeight($item['thumbWidth'], $item['thumbHeight'], $params['type']);
            array_push($goodsIds, $item['id']);

            if ($userType == 1) {
                $price = $item['minPurPrice'];
            } else {
                $price = $item['minPrice'] == 0 ? $item['price'] : $item['minPrice'];
            }

            // todo get price for first rule
            // $rule = $this->_rule($item['id']);
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => thumb($item['thumb'], $wh['width'], $wh['height']),
                'width' => $wh['width'],
                'height' => $wh['height'],
                'price' => money_format('%i', $price / 100),
                'expressWeight' => doubleval($item['expressWeight']),
                'created' => formateTimeStamp($item['created']),
                'isCollected' => false,
                'isAddToCar' => false,
                'isLive' => !empty($item['liveUrl']),
                'liveUrl' => value($item, 'liveUrl', '')
            );
        }

        if (!empty($params['userId'])) {
            $collects = $this->_getCollects($params['userId'], $goodsIds);
            $cars = $this->_getCars($params['userId'], $goodsIds);
            foreach ($results as &$item) {
                $id = $item['goodsId'];
                if (!empty($collects) && in_array($id, $collects)) {
                    $item['isCollected'] = true;
                }

                if (!empty($cars) && in_array($id, $cars)) {
                    $item['isAddToCar'] = true;
                }
            }
        }

        return $results;
    }

    /**
     * rule
     * @param $goodsID
     * @return mixed
     */
    private function _rule($goodsID)
    {
        $db = clone($this->db);
        $query = $db->where(['goods_id' => $goodsID])->order_by('id', 'ASC')->get('base_goods_rule');

        return $query->row_array();
    }

    /**
     * 组合直播流
     * @param $results
     * @param $ids
     * @return mixed
     */
    private function _compileStream($results, $ids)
    {
        if (!empty($ids)) {
            $ids = array_filter($ids, function ($val) {
                return !empty($val);
            });
            $q = $this->db->select('s.id, s.videoUrlHD, s.videoUrlSD')
                ->from('stream_device as s')
                ->where(array('status' => 1))
                ->where_in('s.id', $ids)
                ->get();
            $streams = $q->result_array();
            $streamUrls = [];
            if (!empty($streams)) foreach($streams as $s) {
                $id = $s['id'];
                $streamUrls[$id] = array(
                    'videlUrlHD' => value($s, 'videoUrlHD', ''),
                    'videoUrlSD' => value($s, 'videoUrlSD', '')
                );
            }

            foreach ($results as &$item) {
                $sId = $item['streamId'];
                unset($item['streamId']);
                if (array_key_exists($sId, $streamUrls)) {
                    $item['live'] = $streamUrls[$sId];
                }
            }
        }
        return $results;
    }
}

